<?php

namespace app\controllers;

use app\models\Good;
use app\models\Category;
use app\models\GoodPrice;
use app\models\Specs;
use app\models\Article;
use app\models\Setting;
use app\tools\Re;
use app\filters\auth\HttpBearerAuth;
use yii\helpers\ArrayHelper;
use Yii;

class GoodController extends BaseController
{
    public $unit_typr_arr = ['', '时', '天','月'];

    public function behaviors() {
        $optional =  [
          'cate-list',
          'good-list',
          'good-info',
          'article',
        ];
        return ArrayHelper::merge(parent::behaviors(), [
          'authenticator' => [
            'class' => HttpBearerAuth::class,
            'optional' =>$optional
          ]
        ]);
    }

    //商城公告
    public function actionArticle(){
      $article_list = Article::find()
        ->where(['cate_id' => 6, 'status' => 1])
        ->orderBy("created_at desc")
        ->limit(1)
        ->all();
      $article_data = [];
      if ($article_list) {
        foreach ($article_list as $v) {
          $article_data[] = [
            'id' => $v->id,
            'title' => $v->title,
            'content' => $this->getContent($v->content)
          ];
        }
      }
      return Re::data(['data' => $article_data]);
    }

    //商品类型
    public function actionCateList(){
      $cate_list = Category::find()->where(['type' => 2, 'status' => 1])->all();
      $cate_data = [];
      if ($cate_list) {
        foreach ($cate_list as $v) {
          $cate_data[] = [
            'id' => $v->id,
            'name' => $v->name,
            'icon' => $v->icon.'?imageslim',
          ];
        }
      }
      return Re::data(['data' => $cate_data]);
    }

    //首页接口
    public function actionGoodList(){
      $page = Yii::$app->request->post('page', 0);
      $type = Yii::$app->request->post('type', 1);
      $cate_id = Yii::$app->request->post('cate_id', 0);
      $keyword = Yii::$app->request->post('keyword', '');
      $setting = Setting::findOne(1);
      $good_query = Good::find()->where(['type' => $type, 'status' => 1]);
      /*if (!$setting->order_pay) {//不需要支付，只展示租赁商品
        $good_query->andWhere(['is_zl' => 1]);
      }*/ //2022-04-21取消限制
      // if ($type == 2) {
      //   $good_query->andWhere(['audit_status' => 1]);
      // }
      if ($cate_id) {
        $good_query->andWhere(['cate_id' => $cate_id]);
      }
      if ($keyword) {
        $good_query->andWhere(['like', 'name', $keyword]);
      }
      $good_list = $good_query->limit(10)->offset(10*$page)->orderBy('sort desc, created_at desc')->all();
      $good_data = [];
      if ($good_list) {
        foreach ($good_list as $v) {
          $good_price_list = GoodPrice::find()->where(['good_id' => $v->id])->orderBy('specs_price asc')->all();
          /*if (count($good_price_list) == 1) {
            $price = $good_price_list[0]->specs_price;
          } else {
            $index = count($good_price_list) - 1;
            $price = $good_price_list[0]->specs_price.'-'.$good_price_list[$index]->specs_price;
          }*/
          $price = $v->is_have_specs ? $good_price_list[0]->specs_price : $v->price;
          $good_data[] = [
            'id' => $v->id,
            'name' => $v->name,
            'cover' => $v->cover.'?imageslim',
            'cate_name' => $v->cate->name,
            'price' => $price,
            'good_type' => $v->type,
            'good_zl' => $v->is_zl,
            'unit' => $v->unit,
            'unit_type' => $v->unit_type,
            'sale_count' => $v->sale_count,
          ];
        }
      }
      return Re::data(['data' => $good_data]);
    }

    //商品详情
    public function actionGoodInfo(){
      $id = Yii::$app->request->post('id', 0);
      $good_info = Good::findOne($id);
      if (empty($good_info)) {
        return Re::data(null, '商品信息读取错误', Re::ERROR);
      }
      $good_price_list = GoodPrice::find()->where(['good_id' => $id])->orderBy('specs_price asc')->all();
      /*if (count($good_price_list) == 1) {
        $price = $good_price_list[0]->specs_price;
      } else {
        $index = count($good_price_list) - 1;
        $price = $good_price_list[0]->specs_price.'-'.$good_price_list[$index]->specs_price;
      }*/
      $price = $good_info->is_have_specs ? $good_price_list[0]->specs_price : $good_info->price;
      $good_price_data = [];
      $specs_data = [];
      $specs_one_list = Specs::find()->where(['parent_id' => 0, 'status' => 1])->all();
      if ($specs_one_list && $good_info->is_have_specs) {
        foreach ($specs_one_list as $v1) {
          $specs_two_data = [];
          $specs_two_list = Specs::find()->where(['parent_id' => $v1->id, 'status' => 1])->andWhere("id in (".$good_info->specs_ids.")")->all();
          if ($specs_two_list) {
            foreach ($specs_two_list as $v2) {
              $specs_two_data[] = [
                'id' => $v2->id,
                'name' => $v2->name,
                'code' => $v2->code,
              ];
            }
            $specs_data[] = [
              'name' => $v1->name,
              'child_specs_list' => $specs_two_data,
            ];
          }
        }
      }
      if ($good_price_list && $good_info->is_have_specs) {
        foreach ($good_price_list as $v) {
          $good_price_data[] = [
            'specs_code' => $v->specs_code,
            'specs_name' => $v->specs_name,
            'specs_price' => $v->specs_price,
          ];
        }
      }
      $setting = Setting::findOne(1);
      $unit_type_name = $good_info->unit_type == 2 ? '天' : '月';
      $data = [
        'id' => $id,
        'name' => $good_info->name,
        'cover' => $good_info->cover.'?imageslim',
        'cate_id' => $good_info->cate_id,
        'cate_name' => $good_info->cate->name,
        'content' => $good_info->content,
        //'content' => '',
        'price' => $price,
        'good_type' => $good_info->type,
        'good_zl' => $good_info->is_zl,
        'unit_type' => $good_info->unit_type,
        'unit' => $good_info->unit .'/'. $unit_type_name,
        'specs_list' => $specs_data,
        'price_list' => $good_price_data,
        'imgs' => $good_info->imgs,
        'contact_name' => $good_info->contact_name,
        'contact_phone' => $setting->contact,
        'sale_count' => $good_info->sale_count
      ];
      return Re::data(['data' => $data]);
    }

    //个人发布商品列表
    public function actionMyGoodList(){
      $page = Yii::$app->request->post('page', 0);
      $status = Yii::$app->request->post('status', -1);
      $good_query = Good::find()->where(['user_id' => Yii::$app->user->id, 'type' => 3]);
      if ($status > -1) {
        $good_query->andWhere(['status' => $status]);
      }
      $good_list = $good_query->limit(10)->offset(10*$page)->orderBy('created_at desc')->all();
      $good_data = [];
      if ($good_list) {
        foreach ($good_list as $v) {
          $good_data[] = [
            'id' => $v->id,
            'name' => $v->name,
            'cover' => $v->cover.'?imageslim',
            'cate_name' => $v->cate->name,
            'price' => $v->price,
            'unit' => $this->unit_typr_arr[$v->unit_type],
            'status' => $v->status,
          ];
        }
      }
      return Re::data(['data' => $good_data]);
    }

    //修改个人发布商品状态
    public function actionChangeGoodStatus(){
      $id = Yii::$app->request->post('id', 0);
      $status = Yii::$app->request->post('status', 1);//0:下架 1:上架
      $good = Good::findOne($id);
      if (!$good) {
  			return Re::data(null, '商品信息读取失败', Re::ERROR);
  		}
      $good->status = $status;
      $good->save();
      return Re::data();
    }

    //用户发布/修改商品
    public function actionEditGood(){
      $id = Yii::$app->request->post('id', 0);
      $imgs = Yii::$app->request->post('imgs', '');
      $cate_id = Yii::$app->request->post('cate_id', 0);
      $name = Yii::$app->request->post('name', '');
      $unit_type = Yii::$app->request->post('unit_type', 1);
      $price = Yii::$app->request->post('price', 0);
      $content = Yii::$app->request->post('content', '');
      $contact_name = Yii::$app->request->post('contact_name', '');
      $contact_phone = Yii::$app->request->post('contact_phone', '');
      if (empty($imgs) || empty($cate_id) || empty($name) || empty($unit_type) || empty($price) || empty($content) || empty($contact_name) || empty($contact_phone)) {
        return Re::data(null, '参数错误', Re::ERROR);
      }
      if ($id) {
        $good = Good::findOne($id);
        if (!$good) {
    			return Re::data(null, '商品信息读取失败', Re::ERROR);
    		}
      } else {
        $good = new Good();
      }
      $img_arr = explode(',', $imgs);
      $good->user_id = Yii::$app->user->id;
      $good->name = $name;
      $good->cover = $img_arr[0];
      $good->cate_id = $cate_id;
      $good->content = $content;
      $good->type = 3;
      $good->unit_type = $unit_type;
      $good->imgs = $imgs;
      $good->price = $price;
      $good->contact_name = $contact_name;
      $good->contact_phone = $contact_phone;
      $good->save();
      return Re::data();
    }

    private function getContent($content) {
      $content= str_replace("&nbsp;", "",$content);
      $content = strip_tags($content);
      $content = trim($content);
      return mb_substr($content, 0, 20, 'utf-8');
    }
}
